import httpFetch from 'share/httpFetch';
import config from 'config';
import errorMessage from 'share/errorMessage';
import {grantArr} from "containers/data-center/report-distribution/report-permission.model";
// 权限:缓存起来
let permissionCodesArr = [];
export default {
  getReportDetail(params) {
    // let params = {
    //   id:
    // }
    return new Promise(function (resolve, reject) {
      httpFetch.get(config.baseUrl + '/report/api/report/origin/detail', params)
        .then(function (response) {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  //编辑报表
  updateReport(report) {
    return new Promise(function (resolve, reject) {
      httpFetch.put(config.baseUrl + '/report/api/self/define/report', report)
        .then(function (response) {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  //新增报表（占时不支持修改）
  createReport(report) {
    return new Promise(function (resolve, reject) {
      httpFetch.post(config.baseUrl + '/report/api/report/create', report)
        .then(function (response) {
          resolve(response)
        })
        .catch(function (err) {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // 管理员-所有报表列表,只有公司或者租户管理员才有权限访问
  // 用来分配
  getReportAllList(params) {
    // let params = {
    //   page:0,
    //   size:10
    // }
    return new Promise((resolve, reject) => {
      httpFetch.get(config.baseUrl + '/report/api/report/alllist', params)
        .then((response) => {
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  //获取此报表已经被分配的角色，条件等
  getReportGrantList(params) {
    return new Promise((resolve, reject) => {
      httpFetch.get(config.baseUrl + '/report/api/report/grant', params)
        .then((response) => {
          response.data.map((item, index) => {
            // 参考模型，前端添加两个字段，用于显示
            item = this.getViewGrantName(item);
            item = this.getViewPermissionName(item);
            item.index = index + params.page * params.size + 1;
          });
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // 获取显示的字段根据 permissionDes
  getViewPermissionName(item) {
    if (item.permissionDes) {
      let grant = getNameArrByValue(item.permissionDes, permissionCodesArr);
      item._permission = grant.value;
      item._permissionName = grant.name.join('；');
    } else {
      item._permission = undefined;
      item._permissionName = undefined;
    }
    return item;

    function getNameArrByValue(arr, permissionCodesArr) {
      let res = {};
      res.value = [];
      res.name = [];
      arr.map((item, index) => {
        let grant = getNameByValue(item, permissionCodesArr);
        res.value.push(grant.value);
        res.name.push(grant.name);
      });
      //去重
      res.value = [...new Set(res.value)];
      res.name = [...new Set(res.name)];
      return res
    }

    function getNameByValue(grantProp, permissionCodesArr) {
      let t = {
        name: undefined,
        value: undefined
      };
      permissionCodesArr.map(item => {
        if (grantProp === item.permission_prop) {
          t.name = item.permission_desc;
          t.value = item.permission_prop;
        }
      });
      return t;
    }
  },
  //编辑时 获取显示的字段根据 permissionDes
  getViewPermissionNameDetail(item) {
    if (item.permission && item.permission.length && item.permission.length > 0) {
      let grant = getNameArrByValue(item.permission, permissionCodesArr);
      item._permission = grant.value;
      item._permissionName = grant.name.join('；');
    } else {
      item._permission = undefined;
      item._permissionName = undefined;
    }
    return item;

    function getNameArrByValue(arr, permissionCodesArr) {
      let res = {};
      res.value = [];
      res.name = [];
      arr.map((item, index) => {
        // 与 getViewPermissionName  函数功能不一样
        let grant = getNameByValue(item.permissionProp, permissionCodesArr);
        res.value.push(grant.value);
        res.name.push(grant.name);
      });
      //去重
      res.value = [...new Set(res.value)];
      res.name = [...new Set(res.name)];
      return res
    }

    function getNameByValue(grantProp, permissionCodesArr) {
      let t = {
        name: undefined,
        value: undefined
      };
      permissionCodesArr.map(item => {
        if (grantProp === item.permission_prop) {
          t.name = item.permission_desc;
          t.value = item.permission_prop;
        }
      });
      return t;
    }
  },
  // 获取显示的字段根据 grantDes
  getViewGrantName(item) {
    if (item.grantDes) {
      let grant = getNameByValue(item.grantDes, grantArr);
      item._grant = grant.value;
      item._grantName = grant.name;
    } else {
      item._grant = undefined;
      item._grantName = undefined;
    }
    return item;

    function getNameByValue(grantProp, grantArr) {
      let t = {
        name: undefined,
        value: undefined
      };
      grantArr.map(item => {
        if (grantProp === item.value) {
          t.name = item.name;
          t.value = item.value;
        }
      });
      return t;
    }
  },
  // 获取显示的字段根据 grantDes
  getViewGrantNameDetail(item) {
    if (item.grant && item.grant.length && item.grant.length > 0) {
      let grant = getNameByValue(item.grant[0].grantProp, grantArr);
      item._grant = grant.value;
      item._grantName = grant.name;
    } else if (item.grant && item.grant.length && item.grant.length === 0) {
      //这种是查询详情的时候，查询了人（这是一种兼容的写法）
      let grant = getNameByValue("user", grantArr);
      item._grant = grant.value;
      item._grantName = grant.name;
    } else if (item.grant === undefined) {
      //这种是查询详情的时候，没有查询人
      let grant = getNameByValue("user", grantArr);
      item._grant = grant.value;
      item._grantName = grant.name;
    } else {
      item._grant = undefined;
      item._grantName = undefined;
    }
    return item;

    function getNameByValue(grantProp, grantArr) {
      let t = {
        name: undefined,
        value: undefined
      };
      grantArr.map(item => {
        if (grantProp === item.value) {
          t.name = item.name;
          t.value = item.value;
        }
      });
      return t;
    }
  },
  // 获取报表分配范围值列表
  getPermissionList() {
    return new Promise((resolve, reject) => {
      if (permissionCodesArr.length > 0) {
        resolve(permissionCodesArr)
      } else {
        httpFetch.get(config.baseUrl + '/report/api/report/permissionCodes')
          .then((response) => {
            permissionCodesArr = response.data;
            resolve(response.data)
          })
          .catch((err) => {
            errorMessage(err.response);
            reject(err.response);
          })
      }

    })
  },
  getReportPermissionDetail(obj) {
    // let obj = {
    //   id,
    //   grantCode:"user"
    // }
    return new Promise((resolve, reject) => {
      httpFetch.get(config.baseUrl + '/report/api/report/grant/details', obj)
        .then((response) => {
          response.data = this.getViewGrantNameDetail(response.data);
          response.data = this.getViewPermissionNameDetail(response.data);
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // 创建或者修改报表权限
  // 针对自定义人，新增或者删掉另外走接口
  updateReportPermission(obj) {
    // let obj = {
    //   "sourceReportId": "2",
    //   "reportDesc": "test",
    //   "enable": true,
    //   "delete": false,
    //   "grant": [{
    //     "id": "2",
    //     "grantProp": "user",
    //     "grantValue": "30e5c3a7-86df-46c4-ac6d-267e05d6416f"
    //   }],
    //   "permission":[{
    //     "permissionProp": "sob",
    //     "permissionValue": "950557031234805761"
    //   },
    //     {
    //       "id": "2",
    //       "permissionProp": "user_dept_full",
    //       "permissionValue": "a55a352a-80db-4fbd-9d51-8db49dfe269d"
    //     }
    //   ]
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/report/api/report/grant', obj)
        .then((response) => {
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  getReportPermissionUser(obj, type) {
    // let obj={
    //   "id": "2", //新建分配不填，删除时传入,有id会执行删除动作
    //   "page": "",
    //   "size": "--"
    // }
    obj.grantCode = type;
    return new Promise((resolve, reject) => {
      httpFetch.get(config.baseUrl + '/report/api/report/grant/user', obj)
        .then((response) => {
          if (type === "user") {
            let users = [];
            response.data.map(item => {
              let user = item.user ? item.user : {};
              user._origin = item;
              users.push(user);
            });
            response.data.users = users;
          }
          if (type === "userGroup") {
            let userGroups = [];
            response.data.map(item => {
              let userGroup = item.userGroup ? item.userGroup : {};
              userGroup._origin = item;
              userGroups.push(userGroup);
            });
            response.data.userGroups = userGroups;
          }

          resolve(response);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },

  updateReportPermissionUser(obj) {
    // let obj={
    //   "sourceReportId": "2",
    //   "permission":[],
    //   "grant": [{
    //     "id": "2", //新建分配不填，删除时传入,有id会执行删除动作
    //     "grantProp": "user",
    //     "grantValue": "30e5c3a7-86df-46c4-ac6d-267e05d6416f"
    //    }]
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/report/api/report/grant/user', obj)
        .then((response) => {
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
}
